//
//  PlayViewController.m
//  doubanFun
//
//  Created by bing on 16/3/24.
//  Copyright © 2016年 bing. All rights reserved.
//

#import "RESTClient.h"
#import "AppDelegate.h"
#import "DFSongPlayer.h"
#import "PlayViewController.h"

#define TimeLineHeight 3.0

@interface PlayViewController ()
<DFSongPlayerDelegate>
@property (nonatomic, strong) DFSong *song;
@property (nonatomic, strong) DFSongPlayer *player;
@property (nonatomic, strong) NSArray *songArray;
@property (nonatomic, weak) CAShapeLayer *shapeLayer;
@property (weak, nonatomic) IBOutlet UIButton *playButton;
@property (weak, nonatomic) IBOutlet UIButton *rateButton;

@end

@implementation PlayViewController

- (void)setup {
    // 添加时间线
    CAShapeLayer *layer = [[CAShapeLayer alloc] init];
    layer.frame       = CGRectMake(0, TimeLineHeight/2, SCREEN_WIDTH, TimeLineHeight);
    layer.strokeColor = [UIHelper getColorFromRGB:0xa9b7b7].CGColor;
    layer.fillColor   = [UIColor clearColor].CGColor;
    layer.lineWidth   = TimeLineHeight;
    layer.strokeStart = 0.0;
    layer.strokeEnd   = 0.0;
    _shapeLayer = layer;
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(0, 0)];
    [path addLineToPoint:CGPointMake(SCREEN_WIDTH, 0)];
    [self.view.layer addSublayer:layer];
    layer.path = path.CGPath;
    
    [self.playButton addTarget:self action:@selector(actionSong:) forControlEvents:UIControlEventTouchUpInside];
    
    // 初始化播放器
    DFSongPlayer *player = [DFSongPlayer sharedplayer];
    player.delegate = self;
    _player = player;
    
    // 注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userLoginSuccess:)
                                                 name:USER_LOGIN_SUCCESS object:nil];
    
    
    // 已经登录后默认播放音乐
    NSString *userID = _AppDelegate.user.userID;
    if (userID.length > 0) {
        [self loadDataCallback:^(DFSong *song) {
            [self actionSong:nil];
        }];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setup];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark - loadData
// 加载歌单
- (void)loadDataCallback:(void(^)(DFSong *song))callback  {
    // 频道
    NSString *channelID = _AppDelegate.config.currentChannelID;
    if (channelID.length < 1) {
        [self loadChannelsWithSuccess:^(void) {
            [self loadSongListWithparameters:nil callback:callback];
        }];
        return;
    }
    
    // 歌曲
    [self loadSongListWithparameters:nil callback:callback];
}

// 获取歌单
- (void)loadSongListWithparameters:(NSDictionary *)parameters callback:(void(^)(DFSong *song))callback {
    NSString *url = [NSString stringWithUTF8String:API_SONG];
    if (!parameters) {
        parameters = [self setupNew];
    }
    [_RESTClient method:GET urlString:url parameters:parameters success:^(id responseObject) {
        
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSArray *array =  [responseObject objectForKey:@"song"];
            NSMutableArray *songs = [NSMutableArray arrayWithCapacity:array.count];
            for (NSDictionary *jsonData in array) {
                DFSong *song = [DFSong initWithDictionary:jsonData];
                if (song) {
                    [songs addObject:song];
                }
            }
            [[ChannelPool sharedPool] setSongs:songs channelID:_AppDelegate.config.currentChannelID];
            
            if (callback) {
                callback(songs.firstObject);
            }
        }
        
    } failure:^(NSError *error) {
        NSLog(@"获取 song 错误");
        if (callback) {
            callback(nil);
        }
    }];
}

// 获取频道,有数据库就可以获取数据
- (void)loadChannelsWithSuccess:(void (^)(void))success {
    
    // 本地数据已经初始化过了
    if (_AppDelegate.config.currentChannelID.length > 0) {
        if (success) {
            success();
        }
        return;
    }
    
    // 需要网络数据
    NSString *url = [NSString stringWithUTF8String:API_CHANNELS];
    [_RESTClient method:GET urlString:url parameters:nil success:^(id responseObject) {
        
        NSArray *channels = [responseObject objectForKey:@"channels"];
        if ([channels isKindOfClass:[NSArray class]]) {
            
            NSMutableArray *array = [NSMutableArray array];
            for (NSDictionary *jsonData in channels) {
                DFChannel *channel = [DFChannel initWithDictionary:jsonData];
                if (channel) {
                    [array addObject:channel];
                }
            }
            [[ChannelPool sharedPool] setChannelsArray:array];
            _AppDelegate.config.currentChannelID = [((DFChannel *)array.firstObject) channel_id];
            
            // 需要刷新频道数据
            [[NSNotificationCenter defaultCenter] postNotificationName:CHANNEL_LOAD_SUCCESS object:nil];
        }
            
        if (success) {
            success();
        }
        
    } failure:^(NSError *error) {
        NSLog(@"CHANNEL_LOAD_SUCCESS:%@", error);
    }];
}

// 获取歌词
- (void)loadSonglyric:(DFSong *)song success:(void(^)(void))success {
    NSString *url = [NSString stringWithUTF8String:API_LYRIC];
    NSDictionary *parameters = @{@"sid":song.sid,
                                 @"ssid":song.ssid
                                 };
    [_RESTClient method:POST urlString:url parameters:parameters success:^(id responseObject) {
        
        NSLog(@"lyric:%@", responseObject);
        
    } failure:^(NSError *error) {
        
        NSLog(@"获取歌词错误");
        
    }];
    
}




#pragma mark - 参数
// 没有歌曲播放，歌曲队列也没有任何歌曲，需要返回新播放列表
- (NSDictionary *)setupNew {
    return [self setParametersWithType:@"n" sid:nil];
}

// 歌曲正在播放，队列中还有歌曲，需要返回新的播放列表
- (NSDictionary *)setupPlaying:(NSString *)sid {
    return [self setParametersWithType:@"p" sid:sid];
}

// 不再播放，并返回一个新的歌曲列表,删除一首歌曲
- (NSDictionary *)setupByewithSid:(NSString *)sid {
    return [self setParametersWithType:@"b" sid:sid];
}

// 当前歌曲播放完毕，但是歌曲队列中还有歌曲
- (NSDictionary *)setupEndwithSid:(NSString *)sid {
    return [self setParametersWithType:@"e" sid:sid];
}

// 歌曲正在播放，队列中还有歌曲，适用于用户点击下一首
- (NSDictionary *)setupSkipwithSid:(NSString *)sid {
    return [self setParametersWithType:@"s" sid:sid];
}

// 歌曲正在播放，标记喜欢当前歌曲
- (NSDictionary *)setupRatewithSid:(NSString *)sid {
    return [self setParametersWithType:@"r" sid:sid];
}

// 歌曲正在播放，标记取消喜欢当前歌曲
- (NSDictionary *)setupUnratewithSid:(NSString *)sid {
    return [self setParametersWithType:@"u" sid:sid];
}

- (NSDictionary *)setParametersWithType:(NSString *)type sid:(NSString *)sid {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@"radio_android" forKey:@"app_name"];
    [parameters setObject:@(100) forKey:@"version"];
    [parameters setObject:type forKey:@"type"];
    
    if (sid.length > 0) {
        [parameters setObject:sid forKey:@"sid"];
    }
    
    DFUser *user = _AppDelegate.user;
    if (user) {
        [parameters setObject:user.userID forKey:@"user_id"];
        [parameters setObject:user.expire forKey:@"expire"];
        [parameters setObject:user.token forKey:@"token"];
    }
    
    DFConfig *config = _AppDelegate.config;
    if (config.currentChannelID) {
        [parameters setObject:config.currentChannelID forKey:@"channel"];
    }
    
    return parameters;
}



#pragma mark - action

- (IBAction)next:(id)sender {
    NSLog(@"点击了下一曲");
    [self.player pause];
    [self loadDataCallback:^(DFSong *song) {
        if (song) {
            [self actionSong:nil];
        }
    }];
}

- (IBAction)like:(id)sender {
    
    NSLog(@"点击了喜欢");
    
    if ([_song.like isEqualToNumber:@(1)])
        [self loadSongListWithparameters:[self setupUnratewithSid:_song.sid] callback:nil];
    else
        [self loadSongListWithparameters:[self setupRatewithSid:_song.sid] callback:nil];
    
    DFSong *song = self.song;
    song.like = @(![_song.like boolValue]);
    self.song = song;
}

// 播放按钮
- (void)actionSong:(UIButton *)sender {
    NSLog(@"点击了播放按钮");
    NSString *channelID = _AppDelegate.config.currentChannelID;
    _song = [[ChannelPool sharedPool] songListOfChannelID:channelID].firstObject;
    [self.player setupSongModal:_song];
    if (!_song) {
        [self next:nil];
        return;
    }
    
    // 回调
    if ([self.delegate respondsToSelector:@selector(viewController:playSong:)]) {
        [self.delegate viewController:self playSong:_song];
    }
    
    if ([self.player status] == PALYER_ACTION_STATUS_PLAY)
    {
        [sender setImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
        [self.player pause];
    }
    else
    {
        [sender setImage:[UIImage imageNamed:@"stop"] forState:UIControlStateNormal];
        [self.player play];
    }
}


#pragma mark - DFSongPlayerDelegate
// 播放进度
- (void)player:(DFSongPlayer *)player song:(DFSong *)song currentTime:(NSTimeInterval)currentTime totalTime:(NSTimeInterval)totlatime {
    
    if(self.shapeLayer.strokeStart == 0.0)
    {
        self.shapeLayer.strokeEnd = currentTime/totlatime;
    }
    else if (self.shapeLayer.strokeEnd == 1.0)
    {
        self.shapeLayer.strokeStart = currentTime/totlatime;
    }
}

- (void)player:(DFSongPlayer *)player song:(DFSong *)song loadedProgress:(CGFloat)progress {
//    NSLog(@"缓存进度");
}

- (void)player:(DFSongPlayer *)player endSong:(DFSong *)song {
    NSLog(@"下一首歌曲");
    [self next:nil];
}


- (void)viewController:(ChannelsViewController *)viewVC didChannel:(DFChannel *)channel index:(NSIndexPath *)index {
    NSLog(@"切换频道");
    _AppDelegate.config.currentChannelID = channel.channel_id;
    [self next:nil];
}


#pragma mark - noti

// 用户登录后需要刷新播放列表
- (void)userLoginSuccess:(NSNotification *)noti {
    [self next:nil];
}


#pragma mark -lazy

- (void)setSong:(DFSong *)song {
    _song = song;
    
    if ([song.like isEqualToNumber:@(1)])
        [self.rateButton setImage:[UIImage imageNamed:@"heart_rate"] forState:UIControlStateNormal];
    else
        [self.rateButton setImage:[UIImage imageNamed:@"heart_unrate"] forState:UIControlStateNormal];
    
}

@end
